/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Dao;

import Dao.exceptions.IllegalOrphanException;
import Dao.exceptions.NonexistentEntityException;
import Dao.exceptions.PreexistingEntityException;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import Logica.Evento;
import Logica.Compite;
import Logica.Deportista;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author User
 */
public class DeportistaJpaController implements Serializable {

    public DeportistaJpaController(EntityManagerFactory emf) {
        this.emf = emf;
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Deportista deportista) throws PreexistingEntityException, Exception {
        if (deportista.getCompiteCollection() == null) {
            deportista.setCompiteCollection(new ArrayList<Compite>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Evento idEvento = deportista.getIdEvento();
            if (idEvento != null) {
                idEvento = em.getReference(idEvento.getClass(), idEvento.getIdEvento());
                deportista.setIdEvento(idEvento);
            }
            Collection<Compite> attachedCompiteCollection = new ArrayList<Compite>();
            for (Compite compiteCollectionCompiteToAttach : deportista.getCompiteCollection()) {
                compiteCollectionCompiteToAttach = em.getReference(compiteCollectionCompiteToAttach.getClass(), compiteCollectionCompiteToAttach.getCompitePK());
                attachedCompiteCollection.add(compiteCollectionCompiteToAttach);
            }
            deportista.setCompiteCollection(attachedCompiteCollection);
            em.persist(deportista);
            if (idEvento != null) {
                idEvento.getDeportistaCollection().add(deportista);
                idEvento = em.merge(idEvento);
            }
            for (Compite compiteCollectionCompite : deportista.getCompiteCollection()) {
                Deportista oldDeportistaOfCompiteCollectionCompite = compiteCollectionCompite.getDeportista();
                compiteCollectionCompite.setDeportista(deportista);
                compiteCollectionCompite = em.merge(compiteCollectionCompite);
                if (oldDeportistaOfCompiteCollectionCompite != null) {
                    oldDeportistaOfCompiteCollectionCompite.getCompiteCollection().remove(compiteCollectionCompite);
                    oldDeportistaOfCompiteCollectionCompite = em.merge(oldDeportistaOfCompiteCollectionCompite);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findDeportista(deportista.getIdDeportista()) != null) {
                throw new PreexistingEntityException("Deportista " + deportista + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Deportista deportista) throws IllegalOrphanException, NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Deportista persistentDeportista = em.find(Deportista.class, deportista.getIdDeportista());
            Evento idEventoOld = persistentDeportista.getIdEvento();
            Evento idEventoNew = deportista.getIdEvento();
            Collection<Compite> compiteCollectionOld = persistentDeportista.getCompiteCollection();
            Collection<Compite> compiteCollectionNew = deportista.getCompiteCollection();
            List<String> illegalOrphanMessages = null;
            for (Compite compiteCollectionOldCompite : compiteCollectionOld) {
                if (!compiteCollectionNew.contains(compiteCollectionOldCompite)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Compite " + compiteCollectionOldCompite + " since its deportista field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (idEventoNew != null) {
                idEventoNew = em.getReference(idEventoNew.getClass(), idEventoNew.getIdEvento());
                deportista.setIdEvento(idEventoNew);
            }
            Collection<Compite> attachedCompiteCollectionNew = new ArrayList<Compite>();
            for (Compite compiteCollectionNewCompiteToAttach : compiteCollectionNew) {
                compiteCollectionNewCompiteToAttach = em.getReference(compiteCollectionNewCompiteToAttach.getClass(), compiteCollectionNewCompiteToAttach.getCompitePK());
                attachedCompiteCollectionNew.add(compiteCollectionNewCompiteToAttach);
            }
            compiteCollectionNew = attachedCompiteCollectionNew;
            deportista.setCompiteCollection(compiteCollectionNew);
            deportista = em.merge(deportista);
            if (idEventoOld != null && !idEventoOld.equals(idEventoNew)) {
                idEventoOld.getDeportistaCollection().remove(deportista);
                idEventoOld = em.merge(idEventoOld);
            }
            if (idEventoNew != null && !idEventoNew.equals(idEventoOld)) {
                idEventoNew.getDeportistaCollection().add(deportista);
                idEventoNew = em.merge(idEventoNew);
            }
            for (Compite compiteCollectionNewCompite : compiteCollectionNew) {
                if (!compiteCollectionOld.contains(compiteCollectionNewCompite)) {
                    Deportista oldDeportistaOfCompiteCollectionNewCompite = compiteCollectionNewCompite.getDeportista();
                    compiteCollectionNewCompite.setDeportista(deportista);
                    compiteCollectionNewCompite = em.merge(compiteCollectionNewCompite);
                    if (oldDeportistaOfCompiteCollectionNewCompite != null && !oldDeportistaOfCompiteCollectionNewCompite.equals(deportista)) {
                        oldDeportistaOfCompiteCollectionNewCompite.getCompiteCollection().remove(compiteCollectionNewCompite);
                        oldDeportistaOfCompiteCollectionNewCompite = em.merge(oldDeportistaOfCompiteCollectionNewCompite);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                String id = deportista.getIdDeportista();
                if (findDeportista(id) == null) {
                    throw new NonexistentEntityException("The deportista with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(String id) throws IllegalOrphanException, NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Deportista deportista;
            try {
                deportista = em.getReference(Deportista.class, id);
                deportista.getIdDeportista();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The deportista with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<Compite> compiteCollectionOrphanCheck = deportista.getCompiteCollection();
            for (Compite compiteCollectionOrphanCheckCompite : compiteCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Deportista (" + deportista + ") cannot be destroyed since the Compite " + compiteCollectionOrphanCheckCompite + " in its compiteCollection field has a non-nullable deportista field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Evento idEvento = deportista.getIdEvento();
            if (idEvento != null) {
                idEvento.getDeportistaCollection().remove(deportista);
                idEvento = em.merge(idEvento);
            }
            em.remove(deportista);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Deportista> findDeportistaEntities() {
        return findDeportistaEntities(true, -1, -1);
    }

    public List<Deportista> findDeportistaEntities(int maxResults, int firstResult) {
        return findDeportistaEntities(false, maxResults, firstResult);
    }

    private List<Deportista> findDeportistaEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Deportista.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Deportista findDeportista(String id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Deportista.class, id);
        } finally {
            em.close();
        }
    }

    public int getDeportistaCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Deportista> rt = cq.from(Deportista.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
